<?php

namespace Drupal\commerce_weight_shipping\ViewsController\handler\field;


use views_handler_field_numeric;

class CommerceWeightShippingFirstCostViewsField extends views_handler_field_numeric {

  public function option_definition() {
    $options = parent::option_definition();
    $options['calc'] = ['default' => '/'];
    $options['calc_number'] = ['default' => 100];
    return $options;
  }

  public function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['calc'] = [
      '#type' => 'select',
      '#title' => t('显示计算'),
      '#options' => [
        '' => t('- None -'),
        '+' => t('+'),
        '-' => t('-'),
        '*' => t('*'),
        '/' => t('/'),
      ],
      '#default_value' => $this->options['calc'],
      '#description' => t('在显示前做简单计算，一般用于单位转换.'),
    ];
    $form['calc_number'] = [
      '#type' => 'textfield',
      '#title' => t('计算数'),
      '#default_value' => $this->options['calc_number'],
      '#description' => t('用于计算的另一个数.'),
      '#dependency' => ['edit-options-calc' => ['+', '-', '*', '/']],
    ];
  }

  public function get_value($values, $field = NULL) {
    $value = parent::get_value($values, $field);
    $calc = $this->options['calc'];
    if (!empty($calc)) {
      $calc_number = $this->options['calc_number'];
      switch ($calc) {
        case '+':
          {
            $value = $value + $calc_number;
            break;
          }
        case '-':
          {
            $value = $value - $calc_number;
            break;
          }
        case '*':
          {
            $value = $value * $calc_number;
            break;
          }
        case '/':
          {
            if ($calc_number == 0) {
              $calc_number = 1;
            }
            $value = $value / $calc_number;
            break;
          }
      }
    }
    return $value;
  }
}
